// pages/order/order.js
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    numList: [{
                name: '询价'
              }, {
                name: '下单'
              }, {
                name: '改价'
              }, {
                name: '支付'
              },  {
                name: '交车'
              }, {
                name: '完成'
              }  ],
    num: 1,
    shAddr: '',
    detail: {},
    priceNameInfo: {},
    userInfo: {},
    priceId: '',

    // 优惠券列表
    newUserCoupon: [],
    canUseCoupon: [],
    newUserCouponLenght: 0,
    canUseCouponLenght: 0,
    //弹窗参数
    couponShowList: [],
    chooseCanUseIndex: 0,
    chooseNewUserIndex: 0,
    chooseIndex: 0,
    showType: 0,

    // 弹窗显示标识
    dialogShow: false,

    //未领取标识
    newUserCouponTips: false,
    canUseCouponTips: false,

    //支付金额
    payAmount: 0,
    //优惠金额
    couponAmount: 0,

    saveOrderResult: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    
    this.setData({priceNameInfo: app.globalData.priceNameInfo,userInfo: app.globalData.userInfo})
    var shAddr = wx.getStorageSync('shAddr')
    console.log(shAddr)
    this.setData({ shAddr: shAddr });
    //this.getProduct(options.id)
    this.getProduct(options.id)
    //this.getMyCoupon()
    //this.getCoupon()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var userInfo = app.globalData.userInfo
    console.log("onshow_order",userInfo)
    if(userInfo == null){
      app.wxPublicLogin()
      return false;
    }
    this.getMyCoupon()
    this.getCoupon()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },






  chooseAddress: function () {
    var that = this;
    wx.getSetting({
      success: (res) => {
        console.log(res.authSetting['scope.address'])
        if (res.authSetting['scope.address'] == null) {
          //授权列表中没有收货地址属性，则提示用户主动授权
          wx.authorize({
            scope: 'scope.address',
            complete(res2) {
              console.log(res2)
            }
          })
        } else {
          //授权列表中有收货地址属性
          var address = false;
          address = res.authSetting['scope.address'];
          console.log(address)
          if (address) {
            //已授权
            that.doChooseAddress();
          } else {
            //未授权，提示用户主动授权
            wx.openSetting({
              success: (res) => {
                console.log(res);
              }
            })
          }
        }
      }
    })
  },
  doChooseAddress:function(){
    var that = this;
    wx.chooseAddress({
      success:function(res){
        console.log(res)
        var addr = res.provinceName + res.cityName + res.countyName + res.detailInfo;
        var shAddr = { addr: addr, userName: res.userName, telNumber: res.telNumber};
        that.setData({ shAddr: shAddr });
        wx.setStorageSync("shAddr", shAddr);
      }
    })
  },
  
  getProduct: function(id){
    var that = this
    wx.request({
      url: app.globalData.apiPath + 'product/detail',
      method: 'POST',
      data: {id:id},
      success (res) {
        console.log(res)
        var detail = res.data.data;
        detail.mainImg = JSON.parse(detail.mainImg)
        detail.detailImgs = JSON.parse(detail.detailImgs)
        detail.label = JSON.parse(detail.label)
        var priceId = ''
        if(detail.productPriceList.length > 0){
          detail.defaultPrice = detail.productPriceList[0].price
          priceId = detail.productPriceList[0].id
        }
        if( detail.defaultPrice == null){
          detail.defaultPrice = 0
        }
        var payAmount = detail.deposit+detail.defaultPrice
        that.setData({detail:detail,payAmount:payAmount,priceId:priceId})
      }
    })
},
changeDefaultPrice: function(param){
  var id = param.currentTarget.dataset.id
  var detail = this.data.detail
  var defaultPrice = detail.defaultPrice;
  detail.productPriceList.forEach(item =>{
     if(item.id == id){
        defaultPrice = item.price
     }
  })
  detail.defaultPrice = defaultPrice
  var payAmount = detail.deposit+defaultPrice
  this.setData({payAmount:payAmount,priceId:id,detail:detail})
},
saveOrder:function(){
  var that = this
  if(this.data.shAddr == null || this.data.shAddr.userName == null || this.data.shAddr.telNumber == null || this.data.shAddr.addr == null){
    wx.showToast({title:  "请完善您的地址信息",icon: 'error',duration: 2000 })
    return false;
  }
  var order = {
    productId: this.data.detail.id,
    priceType: this.data.priceId,
    price: this.data.detail.defaultPrice,
    deposit: this.data.detail.deposit,
    totalPrice: this.data.detail.deposit+this.data.detail.defaultPrice,
    payPrice: this.data.payAmount,
    openid: this.data.userInfo.openid,
    type: this.data.detail.sellType,
    shName: this.data.shAddr.userName,
    shPhone: this.data.shAddr.telNumber,
    shAddress: this.data.shAddr.addr
  }
  wx.showLoading({ title: '正在提交', })
  wx.request({
    url: app.globalData.apiPath + 'order/save',
    method: 'POST',
    data: order,
    success (res) {
      wx.hideLoading()
      console.log(res)
      if(res.data.code != 0){
        wx.showToast({title: res.data.msg,icon: 'error',duration: 2000 })
        return false;
      }
      that.setData({saveOrderResult: res.data.data})
      //提交订单完成 修改优惠券使用状态 跳转到指定页面
      if(that.data.couponAmount > 0){
        that.updateCoupon(res.data.data.order.orderSn,order.payPrice)
      }else{
        that.tipsPay(order.payPrice)
      }
     
     
    }
  })
},

//
getMyCoupon: function(){
  var that = this
  wx.request({
    url: app.globalData.apiPath + 'coupon/list',
    method: 'POST',
    data: {openid:this.data.userInfo.openid},
    success (res) {
        var list = res.data.data
        var newUserCoupon = [],canUseCoupon=[]
        list.forEach((item,index) => { 
            if(item.useStatus == 1){
                if(item.type == 0){
                  newUserCoupon.push(item)
                }else {
                  canUseCoupon.push(item)
                }
            }
        })
        
        var couponAmount = 0
        if(newUserCoupon.length > 0){
          couponAmount += newUserCoupon[that.data.chooseNewUserIndex].amount
        }
        if(canUseCoupon.length > 0){
          couponAmount += canUseCoupon[that.data.chooseCanUseIndex].amount
        }
        that.setData({
          newUserCoupon:newUserCoupon,
          canUseCoupon:canUseCoupon,
          newUserCouponLenght: newUserCoupon.length,
          canUseCouponLenght: canUseCoupon.length,
          couponAmount: couponAmount
        })
    }
  })
},

//可用优惠券 提示
getCoupon(){
  var that = this
  wx.request({
    url: app.globalData.apiPath + 'coupon/listAll',
    method: 'POST',
    data: {openid: that.data.userInfo.openid},
    success (res) {
      var list = res.data.data
      list.forEach((item,index) => { 
        //未领取提示
        var canUseCouponTips = false,newUserCouponTips = false;
        if(item.useStatus == null){
           //适用平台
           if(item.type != 0 && (item.platform == 0 || item.platform == that.data.detail.platform)){
                canUseCouponTips = true
           }
           //新人优惠券
           if(item.type == 0){
              newUserCouponTips = true
           }
        }
        that.setData({newUserCouponTips: newUserCouponTips,canUseCouponTips: canUseCouponTips})
    })
    }
  })
},


toCouponPage: function(){
  wx.navigateTo({ url: '/pages/coupon/coupon'})
},
openDialog(param){
  var type = param.currentTarget.dataset.type
  if(type == 0){
    //新人优惠券
    this.setData({couponShowList : this.data.newUserCoupon,chooseIndex: this.data.chooseNewUserIndex})
  }else if(type == 12){
    //优惠券
    this.setData({couponShowList : this.data.canUseCoupon,chooseIndex: this.data.chooseCanUseIndex})
  }
  this.setData({dialogShow: true,showType: type})
},
closeDialog(){
  this.setData({dialogShow: false})
},
chooseCoupon(param){
  var index = param.currentTarget.dataset.index
  var couponAmount = 0
  if(this.data.showType == 0){
    //新人优惠券
    this.setData({chooseNewUserIndex:index,chooseIndex: index})
  }else if(this.data.showType == 12){
    //优惠券
    this.setData({chooseCanUseIndex:index,chooseIndex: index})
  }
  //计算优惠总金额
  if(this.data.newUserCoupon.length > 0){
    couponAmount += this.data.newUserCoupon[this.data.chooseNewUserIndex].amount
  }
  if(this.data.canUseCoupon.length > 0){
    couponAmount += this.data.canUseCoupon[this.data.chooseCanUseIndex].amount
  }
  this.setData({dialogShow:false,couponAmount:couponAmount})
},
updateCoupon(orderSn,payPrice){
    var ids = []
    if(this.data.newUserCoupon.length > 0){
      ids.push(this.data.newUserCoupon[this.data.chooseNewUserIndex].myCouponId)
    }
    if(this.data.canUseCoupon.length > 0){
      ids.push(this.data.canUseCoupon[this.data.chooseCanUseIndex].myCouponId)
    }
    if(ids.length == 0){
      return false;
    }
    var param = {ids:ids,orderSn:orderSn}
    var that = this
    wx.request({
      url: app.globalData.apiPath + 'coupon/batchUpdateStatus2',
      method: 'POST',
      data: param,
      success (res) {
        console.log(res);
        that.tipsPay(payPrice)
      }
    })
},

tipsPay(payPrice){
  var that = this
  if(payPrice == 0){
    wx.showToast({title: "下单成功",icon: 'success',duration: 2000 })
    setTimeout(function(){
      wx.switchTab({url: '/pages/index/index'})
    },2000)
    return false;
  }
  wx.showModal({
    title: '提示',
    content: '订单提交成功，是否立即支付'+payPrice+'元？',
    confirmText: '立即支付',
    cancelText: '稍后支付',
    confirmColor: '#e54d42',
    success (res2) {
      if (res2.confirm) {
        // wx.showToast({ title: '支付成功', icon: 'success',
        //   success: function(){
        //     wx.switchTab({url: '/pages/index/index'})
        //   }
        // })
        //开始支付
        that.doWXPay()
      } else if (res2.cancel) {
        wx.switchTab({url: '/pages/index/index'})
      }
    }
  })
},
doWXPay(){
  var that = this
  var payData = this.data.saveOrderResult.paySign
  console.log(payData)
  wx.requestPayment(
      {
        'timeStamp': payData.timeStamp+'',
        'nonceStr': payData.nonceStr,
        'package': payData.package,
        'signType': payData.signType,
        'paySign': payData.paySign,
        'success': function (e) {  
          //that.updateOrderStatus(res.data.data.ordersno);
          console.log(e)
          that.updateStatus()
        },
        'fail': function (e) { 
          console.log(e)
        },
        'complete': function (e) {
          console.log(e)
          if(e.errMsg == "requestPayment:fail cancel"){
              wx.showToast({title: "取消支付",icon: 'none',duration: 2000 })
          }
          setTimeout(function(){
            wx.redirectTo({ url: '/pages/my-order/my-order' })
          },2000)
        }
      }
  )

},
updateStatus(){
    var id = this.data.saveOrderResult.order.id
    wx.request({
      url: app.globalData.apiPath + 'order/wxPaySuccess',
      method: 'POST',
      data: {id: id},
      success (res) {
        if(res.data.code != 0){
            wx.showToast({title: "状态更新异常",icon: 'error',duration: 2000 }); return false;
        }
        wx.showToast({title: "支付成功",icon: 'none',duration: 2000 })
        setTimeout(function(){
          wx.redirectTo({ url: '/pages/my-order/my-order' })
        },2000)
      }
    })
},




})